﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;
using DG.Tweening;
using Sirenix.OdinInspector;
namespace Miao.UI
{
    /// <summary>
    /// 模仿JRPG游戏的短UI显示对话框，可以设置自动或是手动
    /// </summary>
    abstract public class ShortDialog : UIMotionPanel
    {
        public Typewriter typewriter;
        public int textPtr { get; set; }
        public bool playing;
        /// <summary>
        /// 完成播放回调会在显示完最后一句话后立即调用。
        /// </summary>
        virtual public event Action OnPlayCompleted;
        /// <summary>
        /// 一段话开始播放时回调
        /// </summary>
        public event Action<int> OnLineStart;
        [Tooltip("进行文本回调")]
        public Button NextButton;
        [Title("播放设置")]
        public bool autoPlay;
        public int autoPlayPauseInterval = 2;
        [Tooltip("需要播放的文本")]
        public string[] textQuantity;
        [Tooltip("播放完成后该面板是否隐藏，仍遵守播放延迟设置")]
        public bool CompletedPlayHide = true;

        protected DelayCallHandle delayCallHandle;
        bool handClick;

        public override async Task OnCreate()
        {
            await base.OnCreate();
            NextButton.onClick.AddListener(NextEvent);
        }

        public override void OnClose()
        {
            base.OnClose();
            NextButton.onClick.RemoveListener(NextEvent);
        }

        public void Play()
        {
            textPtr = 0;
            if (textQuantity.Length==0)
            {
                Debug.LogError("对话框文本为空，请检查");
                OnPlayCompleted?.Invoke();
            }
            playing = true;
            PlayInternal();
        }
        protected void PlayInternal()
        {
            OnLineStart?.Invoke(textPtr);
            PlayTypewirter();
            textPtr++;
        }

        virtual protected void PlayTypewirter()
        {
            typewriter.PlayText(textQuantity[textPtr], OnTextCompleted);
        }

        protected void PlayCompleted()
        {
            OnPlayCompleted?.Invoke();
        }

        virtual protected void OnTextCompleted()
        {
            if (autoPlay && textPtr < textQuantity.Length)
            {
                delayCallHandle = MiaoRuntime.Updater.AddDelayCall(PlayInternal, autoPlayPauseInterval);
            }
            else if (textPtr >= textQuantity.Length)
            {
                playing = false;
                PlayCompleted();
                if (CompletedPlayHide && autoPlay)
                {
                    delayCallHandle = MiaoRuntime.Updater.AddDelayCall(Hide,autoPlayPauseInterval);

                }
            }
            // 手动模式下什么都不做，等待用户点击
        }

        public async Task PlayAsyn()
        {
            // 创建一个 TaskCompletionSource 来控制异步操作
            var tcs = new TaskCompletionSource<bool>();
            // 保存原始的完成事件处理器
            var originalHandler = OnPlayCompleted;
            // 临时订阅完成事件，当播放完成时设置任务结果
            Action tempHandler = null;
            tempHandler = () =>
            {
                OnPlayCompleted -= tempHandler; // 取消订阅临时处理器
                tcs.SetResult(true); // 标记任务完成
            };
            OnPlayCompleted += tempHandler;
            Play();
            await tcs.Task;
        }

        /// <summary>
        /// 手动呼叫
        /// </summary>
        virtual public void NextEvent()
        {
            delayCallHandle?.Kill();
            if (typewriter.State == TypewriterState.Outputting)
            {
                handClick = true;
                typewriter.CompleteOutput();
            }
            else//输出完成
            {
                if (textPtr >= textQuantity.Length)
                {
                    if (CompletedPlayHide)
                    {
                        Hide();
                    }
                    return;
                }
                handClick = false;
                PlayInternal();
            }
        }

    }
}